package zkserver

import (
	"core/server/baseserver"
	"core/zookeeper"
	"fmt"
	"github.com/go-zookeeper/zk"
	"sync"
)

type WatchRegServer struct {
	SvrAddr string
	PPath   string
	conn    *zk.Conn
	values  map[string]string
	locker  sync.Mutex
	ch      chan int
	closed  bool
}

func (p *WatchRegServer) Start() {
	p.ch = make(chan int, 1)
	baseserver.AddServer(p)
	p.conn, _ = zookeeper.OpenZK("")

	p.readchild()
	go p.watch()
}
func (p *WatchRegServer) Close() {
	p.closed = true
	p.ch <- 1

}

func (p *WatchRegServer) readchild() error {
	var child, _, err = p.conn.Children(p.PPath)
	if err != nil {
		return err
	}
	var r = make(map[string]string, 0)
	for _, v := range child {
		data, _, err := p.conn.Get(p.PPath + "/" + v)
		if err != nil {
			return err
		}
		r[v] = string(data)
	}
	p.locker.Lock()
	defer p.locker.Unlock()
	p.values = r
	return nil
}
func (p *WatchRegServer) Values() map[string]string {
	p.locker.Lock()
	defer p.locker.Unlock()
	return p.values
}

func (p *WatchRegServer) watch() {
loop:
	if p.closed {
		return
	}
	_, _, ch, err := p.conn.ChildrenW(p.PPath)
	if err != nil {
		fmt.Println(err)
		goto loop
	}
	for {
		select {
		case <-p.ch:

			break
		case e, ok := <-ch:
			fmt.Println(e)
			fmt.Println(ok)
			if !ok {
				goto loop
			}
			p.readchild()
		}
	}
}
